//
//  TKIMLoginViewController.m
//  TKIM
//
//  Created by liupm on 15/10/28.
//  Copyright © 2015年 liupm. All rights reserved.
//

#import "TKIMLoginViewController.h"
#import "TKIMLayerUtils.h"
#import "TKIMLoginView.h"

@interface TKIMLoginViewController () <TKIMManagerDelegate>
@property(nonatomic, strong) TKIMLoginView *loginView;
@end

@implementation TKIMLoginViewController

- (void)loadView {
  [super loadView];
  self.navigationItem.title = @"一创证券";
  self.view.backgroundColor = [UIColor whiteColor];
  _loginView = [[TKIMLoginView alloc] initWithFrame:self.view.frame];
  [self.view addSubview:_loginView];
  [self bindEvent];
}

- (void)viewWillAppear:(BOOL)animated {
  [super viewWillAppear:animated];
  //#warning 防止重复监听
  [[TKIMManager shareInstance] unRegisterDelegate:self];
  //#warning 注册代理监听
  [[TKIMManager shareInstance] registerDelegate:self];
}

- (void)viewDidDisappear:(BOOL)animated {
  [super viewDidDisappear:animated];
  //#warning 解注代理监听
  [[TKIMManager shareInstance] unRegisterDelegate:self];
}

/**
 *  @Author lpm, 15-10-28 12:10:04
 *
 *  @brief  绑定事件
 */
- (void)bindEvent {
  NSString *userName = [TKIMSDKHelper getLoginUserName];
  NSString *password = [TKIMSDKHelper getLoginUserPassword];

  if (userName && userName.length > 0) {

    userName = [userName substringFromIndex:1];
  }

  userName = (NSString *)[TKCacheHelper getItemWithKey:@"User_Name"];

  _loginView.accountTextField.text = userName ? userName : @"";
  _loginView.pwdTextField.text = password ? password : @"";

  [_loginView.loginButton addTarget:self
                             action:@selector(loginOrRegister:)
                   forControlEvents:UIControlEventTouchUpInside];
  [_loginView.registerButton addTarget:self
                                action:@selector(loginOrRegister:)
                      forControlEvents:UIControlEventTouchUpInside];
}

/**
 *  @Author lpm, 15-10-28 12:10:27
 *
 *  @brief  登录
 */
- (void)loginOrRegister:(UIButton *)button {
  [self.view endEditing:YES];

  NSString *userName = _loginView.accountTextField.text;
  if (button.tag == 0) {

    [[TKIMLayerUtils instance] showLoading:YES withLabel:@"...."];

    if (userName && userName.length) {

      [TKIMSDKManager
          initData:[TKIMSDKManager imUDID]
            appkey:APP_SDK_KEY
           apptype:SDKAPPTYPE_CUSTOMER
          custcode:userName
          callback:^(NSInteger errorNumber, NSString *info) {

            if (errorNumber == 0) {

//              [TKIMSDKManager
//                    bindingUser:APP_SDK_KEY
//                       username:userName
//                  callBackBlock:^(NSInteger errorNumber, NSString *info) {
                 [TKIMSDKManager bindingUser:APP_SDK_KEY username:userName memberId:nil callBackBlock:^(NSInteger errorNumber, NSString *info) {
                      
                    // NSLog(@"绑定用户%ld--%@",errorNumber,info);
                    [[TKIMLayerUtils instance] showLoading:NO withLabel:@""];

                    if (errorNumber == 0) {

                      NSLog(@"登录绑定账号");

                      [TKCacheHelper setItem:userName withKey:@"User_Name"];

                      NSLog(@"Alan绑定账号==%ld=%@====%@==%@=%@=%@=%@",
                            (long)errorNumber, info, [TKIMSDKManager imUDID],
                            [TKIMSDKConfig shareInstance].generalUrl,
                            [TKIMCacheHelper valueForKey:TKIMHttpToken],
                            [TKIMSDKManager getLoginUserPuid],
                            [TKIMManager shareInstance].loginUser.userID);

                      [self go];
                    }

                  }];

            } else {

              [[TKIMLayerUtils instance] showTip:info];
            }

          }];

    } else {

      NSString *oldAccount = [TKIMSDKManager getLoginUserPuid];

//      [TKIMSDKManager
//            bindingUser:APP_SDK_KEY
//               username:nil
//          callBackBlock:^(NSInteger errorNumber, NSString *info) {
        [TKIMSDKManager bindingUser:APP_SDK_KEY username:userName memberId:nil callBackBlock:^(NSInteger errorNumber, NSString *info) {

            [[TKIMLayerUtils instance] showLoading:NO withLabel:@""];

            if (errorNumber == 0) {

              NSString *newAccount = [TKIMSDKManager getLoginUserPuid];

              if (![newAccount isEqualToString:oldAccount]) {
                BOOL isShowDetail =
                    [[TKIMSDKUserSet shareInstance] isShowNotifyContent];
                BOOL isOpenSound = [[TKIMSDKUserSet shareInstance] isOpenSound];
                BOOL IsOpenHarassMode =
                    [[TKIMSDKUserSet shareInstance] IsOpenHarassMode];
                NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
                dict[@"appkey"] = APP_SDK_KEY;
                [[TKIMManager shareInstance]
                    uploadPushPreferences:[TKIMSDKHelper getLoginUserName]
                                    token:[TKIMNotificationCenter shareInstance]
                                              .cacheToken
                            isShowContent:isShowDetail
                              isOpenSound:isOpenSound
                          IsOpenNightMode:IsOpenHarassMode
                                    param:dict
                                 callBack:^(TKIMResultVo *resultVo){

                                 }];
              }

              NSLog(@"登录游客");

                NSLog(@"Alan绑定账号==%ld=%@====%@==%@=%@=%@=%@", (long)errorNumber,
                    info, [TKIMSDKManager imUDID],
                    [TKIMSDKConfig shareInstance].generalUrl,
                    [TKIMCacheHelper valueForKey:TKIMHttpToken],
                    [TKIMSDKManager getLoginUserPuid],
                    [TKIMManager shareInstance].loginUser.userID);

              [TKCacheHelper setItem:userName withKey:@"User_Name"];

              [self go];
            }

          }];
    }

  } else {
    [self go];
  }
}

- (void)go {

  NSString *apptype = [TKHttpService app_type];

  if ([@"service" isEqualToString:apptype]) {


  } else {
      TKIMRootViewController *main = [[TKIMRootViewController alloc] init];
      [self.navigationController pushViewController:main animated:YES];
      
//      TKIMUser* user = [[TKIMUser alloc] init];
//      user.isToTop = NO;
//      user.isAttention = YES;
//      user.isAttention = YES;
//      user.isShield  =NO;
//      user.isMember = NO;
//      user.userID  = @"uof2018010817";
//      user.nickName = @"徐文广";
//      user.onlineDescription = @"离线";
//      user.userType  = 0;
//      user.userExt[@"service_code"] = @"100500033";


//      TKIMUser *user = [[TKIMUser alloc] init];
//      user.userID = @"fcsconlineservice";
//      user.nickName = @"在线客服";
//      user.isToTop = YES;
//      user.userType = 0;
//
//      TKIMChatRootViewController *chat = [[TKIMChatRootViewController alloc] init];
//      chat.chatView.user  = user;
//      [[TKIMManager shareInstance] resetUserConverseCount:user.userID];
//      chat.chatView.isKeFu=YES;
//      chat.chatView.channel = 1;
//      [self.navigationController pushViewController:chat animated:YES];
  }
}

#pragma mark 监听代理#pragma mark 监听代理（更多代理可在TKIMManagerDelegate中查看）

//#warning 特别注意以下为im代理监听，必须注册为监听代理才会被调用

/**
 *  @Author lpm, 15-09-17 17:09:37
 *
 *  @brief  服务器返回状态
 *
 *  @param xmppStream
 */
- (void)didReceiveServerStatus:(TKIMStatus *)status {
//  [[TKIMLayerUtils instance] showLoading:NO];
  switch (status.statusCode) {
  case TKIMLoginSuccess: {
    [self routerEventWithName:TKIMLoginSucEvent userInfo:nil];
  } break;
  case TKIMConnectReject:
  case TKIMRegisterSuccess:
  case TKIMRegisterFail:
  case TKIMConnectUnReachable:
  case TKIMAuthenError:
  case TKIMConnectError:
  case TKIMTimeOutError:
  case TKIMServerError: {
    [[TKIMLayerUtils instance] showTip:status.statusInfo];
  } break;
  default:
    break;
  }
}

- (void)routerEventWithName:(NSString *)eventName
                   userInfo:(NSObject *)userInfo {

  if ([eventName isEqualToString:TKIMLoginOutEvent]) {

    [self.navigationController popViewControllerAnimated:YES];
  }
}

@end
